import { createRouter, createWebHashHistory,RouteRecordRaw } from 'vue-router'
import { store } from '@/store'
import { staticRoutes } from '@/router/route'
import { resetRoute } from '@/router/utils'
import { initBackEndControlRoutes } from '@/router/backEnd'
import { initFrontEndControlRoutes } from '@/router/frontEnd'
import NProgress from 'nprogress';
import { Session } from '@/utils/storage'
import { NextLoading } from '@/utils/loading';
import { setFilterRouteEnd } from './utils'

import 'nprogress/nprogress.css';

const router = createRouter({
  history: createWebHashHistory(),
  routes: staticRoutes
})


/**
 * 添加动态路由
 * @method router.addRoute
 * @description 此处循环为 dynamicRoutes（@/router/route）第一个顶级 children 的路由一维数组，非多级嵌套
 * @link 参考：https://next.router.vuejs.org/zh/api/#addroute
 */
 export function setAddRoute() {
	setFilterRouteEnd().forEach((route: RouteRecordRaw) => {
		const routeName: any = route.name
		if (!router.hasRoute(routeName)) {
			router.addRoute(route)
		}
	})
	
}
// isRequestRoutes 为 true，则开启后端控制路由，路径：`/src/store/modules/themeConfig.ts`
const { isRequestRoutes } = store.state.themeConfig.themeConfig;
// 前端控制路由：初始化方法，防止刷新时路由丢失
if (!isRequestRoutes) initFrontEndControlRoutes();
// 全局前置守卫：任何页面的访问都要经过这里
// to：要去哪里的路由信息
// from：从哪里来的路由信息
// next：通行的标志
router.beforeEach(async (to, from, next) => {
  NProgress.configure({ showSpinner: false })
  if (to.meta.title) NProgress.start()
  const cookie = Session.get('cookie')
  if (to.path === '/login' && !cookie) {
		next()
		NProgress.done()
	}else {
    if(!cookie){
      next(`/login?redirect=${to.path}&params=${JSON.stringify(to.query ? to.query : to.params)}`);
			Session.clear();
      resetRoute()
			NProgress.done()
    } else if (cookie && to.path === '/login') {
			// next('/home');
			next('/home');
			NProgress.done();
		}else{
      if (store.state.routesList.routesList.length === 0) {
				if (isRequestRoutes) {
					// 后端控制路由：路由数据初始化，防止刷新时丢失
					await initBackEndControlRoutes();
					// 动态添加路由：防止非首页刷新时跳转回首页的问题
					// 确保 addRoute() 时动态添加的路由已经被完全加载上去
					next({ ...to, replace: true });
				}
			} else {
				next();
			}
    }
  }
})

// 路由加载后
router.afterEach(() => {
	NProgress.done();
	NextLoading.done();
});
export default router
